/*
 * @Author: LMN
 * @Title: 绝对路径改为相对路径脚本
 * @Date: 2019-08-08 19:56:27
 * @LastEditors: LMN
 * @LastEditTime: 2019-08-20 11:07:45
 * @Description: file content
 */
var fs = require('fs')
var path = require('path')

var filePath = path.resolve(__dirname + '/dist')
var dirs = ['css', 'js', 'Config.js']

readDir(filePath, true)

function readDir(path, level) {
  fs.readdir(path, 'utf8', function(err, data) {
    if (!data) return false
    data.forEach(function(item) {
      if ((dirs.indexOf(item) >= 0 && level) || !level) {
        fs.stat(path + '/' + item, function(err, info) {
          if (info.isDirectory()) {
            // console.log('dir:' + item)
            readDir(path + '/' + item)
          } else {
            if (item.indexOf('.css') >= 0 || item.indexOf('.js') >= 0) {
              replacePath(path + '/' + item)
            }
          }
        })
      }
    })
  })
}

function replacePath(path) {
  console.log('\x1B[36m%s\x1B[0m', '替换文件:' + path)
  fs.readFile(path, 'utf8', function(err, files) {
    var result = ''
    // css文件 (font,img)
    if (path.indexOf('.css') >= 0) {
      result = files.replace(/url\(\//g, 'url(../') // url(/ -> url(../
    }
    // js文件 (font,data)
    if (path.indexOf('.js') >= 0) {
      result = files
        .replace(/"\/data\//g, '"data/') // "/data/ -> "data/
        .replace(/'\/data\//g, "'data/") // '/data/ -> 'data/
        .replace(/"\/img\//g, '"img/') // "/img/ -> "img/
        .replace(/'\/img\//g, "'img/") // '/img/ -> 'img/
        .replace(/image:"\/\/\/img\//g, 'image:"//img/') // image:"///img/ -> image:"//img
        .replace(/image:'\/\/\/img\//g, "image:'//img/") // image:'///img/ -> image:'//img
        .replace(/url\(\//g, 'url(') // url(/ -> url(
        .replace(/url\("\//g, 'url("') // url("/ -> url("
        .replace(/url\('\//g, "url('") // url('/ -> url('
    }
    fs.writeFile(path, result, 'utf8', function(err) {
      if (err) return console.log(err)
    })
  })
}
